package flint04
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class BitmapLoader extends EventDispatcher{
		
		public static const BITMAPS_LOADED:String = "bitmapsLoaded";
		
		private var xmlFile:String;
		private var loader:Loader;
		private var bitmapArray:Array;
		
		private var currIndex:Number = -1;					//current index
		private var totalIndex:Number; 						//total number of XML indices
		private var xmlLoader:URLLoader; 					//URL loader
		private var xmlData:XML; 	
		
		public function BitmapLoader(file:String){
			xmlFile = file;
		}
		
		//Return the next bitmap from the loaded array
		public function getNextBitmap():Bitmap{
			
			currIndex +=1;
			
			if(currIndex < totalIndex){
				return Bitmap(bitmapArray[currIndex]);
			}else{
				currIndex = -1;								//reset index pointer
				return Bitmap(bitmapArray[totalIndex-1]);
			}
		}
		
		public function initXML():void{
			//init vars
			currIndex = 0;
			totalIndex = 0;
			xmlLoader = new URLLoader();
			xmlData = new XML();
			
			loader = new Loader();
			
			//load xml file
			xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
			xmlLoader.load(new URLRequest(xmlFile));
		}
		
		//load bitmaps from xml file
		private function xmlLoaded(e:Event):void{
			
			xmlData = XML(xmlLoader.data);
			totalIndex = xmlData.*.length(); 				//get number of xml indices
			bitmapArray = new Array(totalIndex);
			
			var file:String = new String(xmlData.image[currIndex].imgURL);
			
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, addBitmap);
			loader.load(new URLRequest(file));
		}
		
		//if all images loaded: fire a 'BITMAP_LOADED' event
		private function addBitmap(event:Event):void{
			var bitmap:Bitmap = Bitmap(loader.content);
			bitmapArray[currIndex] = bitmap;
			currIndex += 1;
			
			if(currIndex == totalIndex){ 		//if all images loaded
				currIndex = -1;					//reset index pointer
				dispatchEvent(new Event(BITMAPS_LOADED));
			}else{
				var f:String = new String(xmlData.image[currIndex].imgURL);
				loader.load(new URLRequest(f));
			}
		}
	}
}